package com.hjrpc.babyyamall.product.filter;

import com.hjrpc.babyyamall.product.feign.MemberFeignService;
import com.hjrpc.common.constant.AuthServerConstant;
import com.hjrpc.common.dto.LoginUserTo;
import com.hjrpc.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

//@WebFilter(urlPatterns = {"/[.*]+", "/.*?(?<!index)$", "/.*?(?<!index\\.html)$"}
//        , filterName = "ssoTokenFilter")
public class SSOTokenFilter implements Filter {

    @Value("${auth.sso.url}")
    String ssoServerUrl;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    MemberFeignService memberFeignService;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;

        List<Cookie> ssoToken = httpRequest.getCookies() == null ? new ArrayList<>() : Arrays.stream(httpRequest.getCookies())
                .filter(cookie -> cookie.getName().equals("ssoToken"))
                .collect(Collectors.toList());
        // 如果没有token，我们就带上请求路径重定向到
        if (ssoToken.isEmpty()) {
            httpResponse.sendRedirect(ssoServerUrl + "?redirectUrl=" + httpRequest.getRequestURI() + "?" + httpRequest.getQueryString());
        } else {
            String ssoTokenString = ssoToken.get(0).getValue();
            Long memberId = Long.valueOf(redisTemplate.opsForValue().get(AuthServerConstant.AUTH_SSO_TOKEN_PREFIX + ssoTokenString));
            R r = memberFeignService.info(memberId);
            if (r.isSuccess()) {
                LoginUserTo loginUserTo = r.getData(LoginUserTo.class);
                httpRequest.setAttribute("loginUser", loginUserTo);
                Cookie cookie = new Cookie("ssoToken", ssoTokenString);
                httpResponse.addCookie(cookie);
                filterChain.doFilter(servletRequest, servletResponse);
            } else {
                throw new RuntimeException("远程调用出现异常");
            }
        }
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
